
package com.ansion.utils;

import static android.os.Build.VERSION_CODES.R;

import android.app.Activity;
import android.app.ActivityManager;
import android.app.Dialog;
import android.content.ComponentName;
import android.content.Context;
import android.content.pm.ActivityInfo;
import android.content.res.AssetFileDescriptor;
import android.content.res.ColorStateList;
import android.content.res.Configuration;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Point;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.LayerDrawable;
import android.graphics.drawable.RippleDrawable;
import android.graphics.drawable.ShapeDrawable;
import android.graphics.drawable.StateListDrawable;
import android.graphics.drawable.shapes.OvalShape;
import android.graphics.drawable.shapes.RectShape;
import android.graphics.drawable.shapes.RoundRectShape;
import android.graphics.drawable.shapes.Shape;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.DisplayMetrics;
import android.util.StateSet;
import android.view.Display;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.TextView;

import androidx.annotation.ColorInt;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.StringRes;
import androidx.core.text.TextUtilsCompat;
import androidx.core.view.ViewCompat;
import androidx.recyclerview.widget.RecyclerView;
import androidx.recyclerview.widget.SimpleItemAnimator;


import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.List;
import java.util.Locale;

public class UiUtils {
    public static final RectF rectTmp = new RectF();

    private static float density;
    private static final Point displaySize = new Point();
    private static final DisplayMetrics displayMetrics = new DisplayMetrics();

    public static int getAlphaColor(@ColorInt int color, float percent) {
        return ((int) (((color & 0xFF000000) >> 24 & 0xFF) * percent) << 24) | (color & 0x00FFFFFF);
    }

    @Deprecated
    public static float dipFloatToPx(float dip) {
        return dip * getDensity();
    }

    @Deprecated
    public static int dipToPx(float dip) {
        return (int) (dip * getDensity() + 0.5f);
    }

    @Deprecated
    public static int dipToPx(int dip) {
        return (int) (dip * getDensity() + 0.5f);
    }

    @Deprecated
    public static float dipToPxFloat(float dip) {
        return (dip * getDensity() + 0.5f);
    }


    public static float getDensity() {
        return density;
    }

    public static int getScreenWidthPixels() {
        DisplayMetrics dm = new DisplayMetrics();
        ((WindowManager) ResourceUtils.getContext().getSystemService(Context.WINDOW_SERVICE))
                .getDefaultDisplay().getMetrics(dm);
        return dm.widthPixels;
    }

    public static int getScreenHeightPixels() {
        DisplayMetrics dm = new DisplayMetrics();
        ((WindowManager) ResourceUtils.getContext().getSystemService(Context.WINDOW_SERVICE))
                .getDefaultDisplay().getMetrics(dm);
        return dm.heightPixels;
    }

    public static DisplayMetrics getDisplayMetrics() {
        DisplayMetrics dm = new DisplayMetrics();
        ((WindowManager) ResourceUtils.getContext().getSystemService(Context.WINDOW_SERVICE))
                .getDefaultDisplay().getMetrics(dm);
        return dm;
    }

    public static int getRealScreenHeightPixels() {
        DisplayMetrics dm = new DisplayMetrics();
        ((WindowManager) ResourceUtils.getContext().getSystemService(Context.WINDOW_SERVICE))
                .getDefaultDisplay().getRealMetrics(dm);
        return dm.heightPixels;
    }

    @Deprecated
    static public int pxToDip(float px) {
        return (int) (px / getDensity() + 0.5f);
    }

    @Deprecated
    public static int spToPx(float sp) {
        return (int) (sp * getDensity() + 0.5f);
    }

    public static void checkDisplaySize(Context context, @Nullable Configuration newConfiguration) {
        try {
            density = context.getResources().getDisplayMetrics().density;
            Configuration configuration = newConfiguration;
            if (configuration == null) {
                configuration = ResourceUtils.getContext().getResources().getConfiguration();
            }
            WindowManager manager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
            if (manager != null) {
                Display display = manager.getDefaultDisplay();
                if (display != null) {
                    display.getMetrics(displayMetrics);
                    display.getSize(displaySize);
                }
            }
            if (configuration.screenWidthDp != Configuration.SCREEN_WIDTH_DP_UNDEFINED) {
                int newSize = (int) Math.ceil(configuration.screenWidthDp * density);
                if (Math.abs(displaySize.x - newSize) > 3) {
                    displaySize.x = newSize;
                }
            }
            if (configuration.screenHeightDp != Configuration.SCREEN_HEIGHT_DP_UNDEFINED) {
                int newSize = (int) Math.ceil(configuration.screenHeightDp * density);
                if (Math.abs(displaySize.y - newSize) > 3) {
                    displaySize.y = newSize;
                }
            }
        } catch (Exception ignore) {
        }
    }

    public static boolean isLandscape() {
        return displaySize.x > displaySize.y;
    }

    /**
     * get system layout direction
     *
     * @return
     */
    public static boolean isRTL() {
        return TextUtils.getLayoutDirectionFromLocale(Locale.getDefault()) == View.LAYOUT_DIRECTION_RTL;
    }

    public static int[] getScreenSize(Context context) {
        WindowManager windowmanager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
        Display defaultDisplay = windowmanager.getDefaultDisplay();
        DisplayMetrics displayMetrics = new DisplayMetrics();
        defaultDisplay.getMetrics(displayMetrics);
        return new int[]{displayMetrics.widthPixels, displayMetrics.heightPixels};
    }

    public static Bundle mergePayload(List<Bundle> payloads) {
        if (payloads == null || payloads.isEmpty())
            return new Bundle();
        if (payloads.size() == 1)
            return payloads.get(0);
        int size = payloads.size();
        Bundle payload0 = payloads.get(0);
        for (int i = 1; i < size; i++) {
            payload0.putAll(payloads.get(i));
        }
        return payload0;
    }


    /**
     * 修改屏幕方向
     *
     * @return
     */
    public static boolean fixOrientation(Activity activity) {
        try {
            Field field = Activity.class.getDeclaredField("mActivityInfo");
            field.setAccessible(true);
            ActivityInfo o = (ActivityInfo) field.get(activity);
            o.screenOrientation = ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED;
            field.setAccessible(false);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    /**
     * 判断是否是全透明
     *
     * @return
     */
    public static boolean isTranslucentOrFloating(Context context) {
        boolean isTranslucentOrFloating = false;
        try {
            int[] styleableRes = (int[]) Class.forName("com.android.internal.R$styleable").getField("Window").get(null);
            final TypedArray ta = context.obtainStyledAttributes(styleableRes);
            Method m = ActivityInfo.class.getMethod("isTranslucentOrFloating", TypedArray.class);
            m.setAccessible(true);
            isTranslucentOrFloating = (boolean) m.invoke(null, ta);
            m.setAccessible(false);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return isTranslucentOrFloating;
    }


    /**
     * @param button        只接受ImageButtonWithText或者Button
     * @param editTextArray edittext列表
     */
    public static void editCtrlEnable(final Object button, final EditText... editTextArray) {

        if (editTextArray == null || button == null)
            return;
        //初始化的时候检测当前edittext里的值，判断状态。
        boolean isBtnEnable = true;
        for (int i = 0; i < editTextArray.length; i++) {
            if (editTextArray[i] == null) {
                return;
            }
            editTextArray[i].addTextChangedListener(new TextWatcher() {
                @Override
                public void onTextChanged(CharSequence s, int start, int before, int count) {
                }

                @Override
                public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                }

                @Override
                public void afterTextChanged(Editable s) {
                    boolean isBtnEnable = true;
                    //当前输入框不为空，置为true
                    if (!TextUtils.isEmpty(s)) {
                        isBtnEnable = true;
                        //再检测其他输入框是否为空
                        for (int i = 0; i < editTextArray.length; i++) {
                            EditText et = editTextArray[i];
                            if (et != null && TextUtils.isEmpty(et.getText().toString())) {
                                isBtnEnable = false;
                            }
                        }
                    } else {
                        isBtnEnable = false;
                    }
                    if (button instanceof Button) {
                        ((Button) button).setEnabled(isBtnEnable);
                    }

                }
            });

            if (TextUtils.isEmpty(editTextArray[i].getText().toString())) {
                isBtnEnable = false;
            }

        }
        //初始化的时候根据状态控制按钮enable与否
        if (button instanceof Button) {
            ((Button) button).setEnabled(isBtnEnable);
        }

    }


    public static void clearAllViewMember(Object obj) {
        if (obj == null) {
            return;
        }
        try {
            Class<?> cls = obj.getClass();
            if (cls == null) {
                return;
            }
            Field[] flds = cls.getDeclaredFields();
            if (flds == null) {
                return;
            }
            for (Field fld : flds) {
                String name = fld.getName();
                // LogUtil.debug(TAG, "check:" + name);
                if (!name.startsWith("m_")) {
                    continue;
                }
                int modify = fld.getModifiers();
                if (Modifier.isStatic(modify)) {
                    continue;
                }
                if (Modifier.isFinal(modify)) {
                    continue;
                }
                if (Modifier.isPublic(modify)) {
                    continue;
                }
                fld.setAccessible(true);
                Object fieldValue = fld.get(obj);
                if (fieldValue == null) {
                    // LogUtil.debug(TAG, "null:" + name);
                    continue;
                }
                if (fieldValue instanceof View || fieldValue instanceof Bitmap
                        || fieldValue instanceof Drawable
                        || fieldValue instanceof Context
                        || fieldValue instanceof Dialog
                        || fieldValue instanceof Handler
                        || fieldValue instanceof BaseAdapter
                        || fieldValue instanceof Animation
                        || fieldValue instanceof AssetFileDescriptor) {
                    // LogUtil.debug(TAG, "clear:" + name);
                    fld.set(obj, null);
                }
            }
        } catch (Exception e) {
            // LogUtil.error(TAG, e);
        }
    }

    public static boolean isRTLLanguage() {
//		Configuration config = BOTApplication.getContext().getResources().getConfiguration();
//		return LayoutDirection.RTL == config.getLayoutDirection();
        int direction = TextUtilsCompat.getLayoutDirectionFromLocale(Locale.getDefault());
        return direction == ViewCompat.LAYOUT_DIRECTION_RTL;
    }

    public static void setLayerType(View v, int layerType, Paint paint) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
            v.setLayerType(layerType, paint);
        }
    }

    public static float getPixelsInCM(float cm, boolean isX) {
        DisplayMetrics displayMetrics = ResourceUtils.getContext().getResources().getDisplayMetrics();
        return (cm / 2.54f) * (isX ? displayMetrics.xdpi : displayMetrics.ydpi);
    }

//    public static int getToolbarHeight() {
//        return (int) (ResourceUtils.getContext().getResources().getDimension(R.dimen.abc_action_bar_default_height_material));
//    }


    public static boolean isBackground() {
        ActivityManager am = (ActivityManager) ResourceUtils.getContext()
                .getSystemService(Context.ACTIVITY_SERVICE);
        ComponentName cn = am.getRunningTasks(1).get(0).topActivity;
        String currentPackageName = cn.getPackageName();
        if (!TextUtils.isEmpty(currentPackageName)
                && currentPackageName.equals(ResourceUtils.getContext()
                .getPackageName())) {
            return false;
        }
        return true;
    }

    /**
     * 当前Activity是否在最上面
     *
     * @param mActivityName Activity.class.getName()
     * @return
     */
    public static boolean isActivityForeground(String mActivityName) {
        ActivityManager manager = (ActivityManager) ResourceUtils
                .getContext().getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningTaskInfo> runningTasks = manager.getRunningTasks(1);
        if (runningTasks == null || runningTasks.isEmpty()) {
            return false;
        }

        ActivityManager.RunningTaskInfo info = runningTasks.get(0);
        if (info.topActivity == null) {
            return false;
        }
        String className = info.topActivity.getClassName(); // 完整类名
        return mActivityName.equals(className);
    }


    public static final void initCheckBoxCallback(final CompoundButton cb,
                                                  final CompoundButton.OnCheckedChangeListener callback) {
        if (cb == null || callback == null)
            return;
        cb.setTag((Boolean) false);
        cb.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if (event != null
                        && event.getAction() == MotionEvent.ACTION_DOWN)
                    cb.setTag((Boolean) true);
                return false;
            }

        });

        cb.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView,
                                         boolean isChecked) {
                Boolean clickByUser = (Boolean) cb.getTag();
                cb.setTag((Boolean) false);
                if (!clickByUser)
                    return;
                callback.onCheckedChanged(buttonView, isChecked);
            }
        });

    }

    public static void fixGravityAndDirection(TextView textView) {
        if (null == textView) {
            return;
        }
        textView.setTextAlignment(View.TEXT_ALIGNMENT_VIEW_START);
        textView.setTextDirection(View.TEXT_DIRECTION_LTR);
    }




    public final static int getPreImageSize() {
        int size = (int) (210 * getDensity());
        return size;
    }

    @Deprecated
    public final static int scale(int value) {
        return (int) (value * getDensity());
    }

    @Deprecated
    public final static int dp(float value) {
        return (int) Math.ceil(getDensity() * value);
    }

    public final static int rescale(int value) {
        float density = getDensity();
        if (density > 1 && density < 1.5) {
            density = 1.5f;
        }
        return (int) (value * getDensity());
    }

    @Deprecated
    public final static float dip2px(float dpValue) {
        return (dpValue * getDensity());
    }

    @Deprecated
    public final static float px2sp(float pxValue) {
        final float scale = ResourceUtils.getContext().getResources()
                .getDisplayMetrics().scaledDensity;
        return (pxValue / scale);
    }

    /**
     * 获取动画起始位置
     */
    public static int[] getViewLocation(View view) {
        int[] locations = new int[2];
        view.getLocationOnScreen(locations);
        int halfW = view.getWidth() / 2;
        // 设置view中心点为锚点
        locations[0] = locations[0] + halfW;
        locations[1] = locations[1] + halfW;
        return locations;
    }


    /**
     * 判断坐标是否落在特定View内
     */
    public static boolean isLocateAtView(View view, float x, float y) {
        if (view == null) {
            return false;
        }
        int[] location = new int[2];
        view.getLocationOnScreen(location);
        int left = location[0];
        int top = location[1];
        int right = left + view.getWidth();
        int bottom = top + view.getHeight();
        return (x >= left && x <= right && y >= top && y <= bottom);
    }

    /**
     * 当前view是否相交于全局可见矩形
     * <p>
     * 即当前view是否在手机屏幕内（不一定可见）
     * <p>
     * 常用滑动监听 getViewTreeObserver().addOnScrollChangedListener(listener);
     *
     * @param view
     * @return
     */
    public static boolean isViewIntersectScreen(final View view) {
        if (view == null) {
            return false;
        }
        if (!view.isShown()) {
            return false;
        }
        final Rect actualPosition = new Rect();
        view.getGlobalVisibleRect(actualPosition);
        final Rect screen = new Rect(0, 0, getScreenWidthPixels(), getScreenHeightPixels());
        return actualPosition.intersect(screen);
    }


    public static Drawable getStateDrawable(int unSelectedRes, int selectedRes) {
        int selected = android.R.attr.state_selected;
        StateListDrawable stalistDrawable = new StateListDrawable();
        stalistDrawable.addState(new int[]{-selected}, ResourceUtils.getDrawable(unSelectedRes));
        stalistDrawable.addState(new int[]{selected}, ResourceUtils.getDrawable(selectedRes));
        //没有任何状态时显示的图片，我们给它设置我空集合
        stalistDrawable.addState(new int[]{}, ResourceUtils.getDrawable(unSelectedRes));
        return stalistDrawable;
    }

    /***
     * 带有不可用状态的背景图可以用这个方法
     * @param disableDrawable
     * @param enableDrawable
     * @return
     */
    public static Drawable getEnableStateDrawable(Drawable disableDrawable, Drawable enableDrawable) {
        int selected = android.R.attr.state_enabled;
        StateListDrawable stalistDrawable = new StateListDrawable();
        stalistDrawable.addState(new int[]{-selected}, disableDrawable);
        stalistDrawable.addState(new int[]{selected}, enableDrawable);
        return stalistDrawable;
    }


    public static Drawable getLayerDrawable(int bottom, int middle, int top) {
        Drawable[] array = new Drawable[3];
        array[0] = ResourceUtils.getDrawable(bottom);
        array[1] = ResourceUtils.getDrawable(middle);
        array[2] = ResourceUtils.getDrawable(top);
        array[1].setAlpha(0);
        array[2].setAlpha(0);
        LayerDrawable ld = new LayerDrawable(array);
        return ld;
    }


    /***
     * 获取水波纹背景，后续使用代码创建，避免自定义背景太多
     * @param color 默认色
     * @param highlightColor 点击色/水波纹颜色
     * @param radius 圆角半径，单位是dp
     * @return
     */
    public static Drawable getRippleBackground(@ColorInt int color, @ColorInt int
            highlightColor, int radius) {
        Shape shape = null;
        if (radius > 0) {
            float dpValue = dip2px(radius);
            float[] outRadius = new float[]{dpValue, dpValue, dpValue, dpValue, dpValue, dpValue, dpValue, dpValue};
            RoundRectShape roundRectShape = new RoundRectShape(outRadius, null, null);
            shape = roundRectShape;
        } else {
            shape = new RectShape();
        }
        return getRippleBackground(color, highlightColor, shape);
    }

    /***
     * 获取水波纹背景，后续使用代码创建，避免自定义背景太多
     * @param color
     * @param highlightColor
     * @return
     */
    public static Drawable getRippleBackgroundNoRadius(@ColorInt int color, @ColorInt int
            highlightColor) {
        return getRippleBackground(color, highlightColor, new RectShape());
    }

    /***
     * 获取水波纹背景，后续使用代码创建，避免自定义背景太多
     * @param color
     * @param highlightColor
     * @param outRadius
     * @return
     */
    public static Drawable getRippleBackground(@ColorInt int color, @ColorInt int
            highlightColor, float[] outRadius) {
        Shape shape = null;
        if (outRadius != null) {
            RoundRectShape roundRectShape = new RoundRectShape(outRadius, null, null);
            shape = roundRectShape;

        } else {
            RectShape rectShape = new RectShape();
            shape = rectShape;
        }

        return getRippleBackground(color, highlightColor, shape);
    }


    /***
     * 获取水波纹背景，后续使用代码创建，避免自定义背景太多
     * @param color
     * @param highlightColor
     * @param shape 形状，圆形，圆角矩形，矩形
     * @return
     */
    public static Drawable getRippleBackground(@ColorInt int color, @ColorInt int
            highlightColor, Shape shape) {
        int[][] stateList = new int[][]{
                new int[]{android.R.attr.state_pressed},
                new int[]{android.R.attr.state_focused},
                new int[]{android.R.attr.state_activated},
                new int[]{}
        };

        //正常色
        int normalColor = color;
        //按压后的颜色
        int pressedColor = highlightColor;
        int[] stateColorList = new int[]{
                pressedColor,
                pressedColor,
                pressedColor,
                normalColor
        };
        ColorStateList colorStateList = new ColorStateList(stateList, stateColorList);
        ShapeDrawable maskDrawable = new ShapeDrawable();
        maskDrawable.setShape(shape);
        maskDrawable.getPaint().setStyle(Paint.Style.FILL);
        ShapeDrawable defaultDrawable = new ShapeDrawable();
        defaultDrawable.getPaint().setColor(color);
        defaultDrawable.setShape(shape);
        //contentDrawable实际是默认初始化时展示的；maskDrawable 控制了rippleDrawable的范围
        RippleDrawable rippleDrawable = new RippleDrawable(colorStateList, defaultDrawable, maskDrawable);
        return rippleDrawable;
    }


    public static Drawable getCircleBackGround(@ColorInt int mBackGroundColor, @ColorInt int
            mBackGroundColor_true) {
        return getRippleBackground(mBackGroundColor, mBackGroundColor_true, new OvalShape());
    }

    /***
     * 获取带点击态的纯色背景
     * @param rad
     * @param defaultColor 默认颜色
     * @param pressedColor 点击颜色
     * @return
     */
    public static Drawable getStateDrawable(@ColorInt int defaultColor, @ColorInt int pressedColor, int rad) {
        int radius = dp(rad);
        ShapeDrawable defaultDrawable = new ShapeDrawable(new RoundRectShape(new float[]{radius, radius, radius, radius, radius, radius, radius, radius}, null, null));
        defaultDrawable.getPaint().setColor(defaultColor);
        ShapeDrawable pressedDrawable = new ShapeDrawable(new RoundRectShape(new float[]{radius, radius, radius, radius, radius, radius, radius, radius}, null, null));
        pressedDrawable.getPaint().setColor(pressedColor);
        StateListDrawable stateListDrawable = new StateListDrawable();
        stateListDrawable.addState(new int[]{android.R.attr.state_pressed}, pressedDrawable);
        stateListDrawable.addState(new int[]{android.R.attr.state_selected}, pressedDrawable);
        stateListDrawable.addState(StateSet.WILD_CARD, defaultDrawable);
        return stateListDrawable;
    }

    /***
     * 获取纯色背景，后续使用代码创建，避免自定义背景太多
     * @param color
     * @param radius
     * @return
     */
    public static Drawable getBackground(@ColorInt int color, int radius) {
        Shape shape = null;
        if (radius > 0) {
            float dpValue = dp(radius);
            float[] outRadius = new float[]{dpValue, dpValue, dpValue, dpValue, dpValue, dpValue, dpValue, dpValue};
            shape = new RoundRectShape(outRadius, null, null);
        } else {
            shape = new RectShape();
        }
        return getBackground(color, shape);
    }


    public static Drawable getBackground(@ColorInt int color, int topRadius, int bottomRadius) {
        float[] radii = new float[8];
        radii[0] = radii[1] = radii[2] = radii[3] = dp(topRadius);
        radii[4] = radii[5] = radii[6] = radii[7] = dp(bottomRadius);
        RoundRectShape shape = new RoundRectShape(radii, null, null);
        return getBackground(color, shape);
    }

    public static Drawable getBackground(@ColorInt int color, int topLeftRadius, int topRightRadius, int bottomLeftRadius, int bottomRightRadius) {
        float[] radii = new float[8];
        radii[0] = radii[1] = dp(topLeftRadius);
        radii[2] = radii[3] = dp(topRightRadius);
        radii[4] = radii[5] = dp(bottomRightRadius);
        radii[6] = radii[7] = dp(bottomLeftRadius);
        RoundRectShape shape = new RoundRectShape(radii, null, null);
        return getBackground(color, shape);
    }


    /***
     * 获取圆形背景，后续使用代码创建，避免自定义背景太多
     * @param color
     * @return
     */
    public static Drawable getCircleBackGround(@ColorInt int color) {
        return getBackground(color, new OvalShape());
    }


    /***
     * 获取指定形状的纯色背景，后续使用代码创建，避免自定义背景太多
     * @param color 背景色
     * @param shape 形状，圆形，圆角矩形，矩形
     * @return
     */
    public static Drawable getBackground(@ColorInt int color, Shape shape) {
        ShapeDrawable shapeDrawable = new ShapeDrawable();
        shapeDrawable.getPaint().setColor(color);
        shapeDrawable.setShape(shape);
        return shapeDrawable;
    }

    public static Bundle mergePayloads(@NonNull List<Object> payloads) {
        Bundle mergedPayload = new Bundle();
        final int size = payloads.size();
        for (int i = 0; i < size; i++) {
            Object o = payloads.get(i);
            Bundle bundle;
            if (o instanceof Bundle) {
                bundle = (Bundle) o;
            } else {
                continue;
            }
            mergedPayload.putAll(bundle);
        }

        return mergedPayload;
    }

    public static void clearItemAnimator(RecyclerView recyclerView) {
        RecyclerView.ItemAnimator itemAnimator = recyclerView.getItemAnimator();
        if (itemAnimator != null) {
            itemAnimator.setAddDuration(0);
            itemAnimator.setChangeDuration(0);
            itemAnimator.setMoveDuration(0);
            itemAnimator.setRemoveDuration(0);
            if (itemAnimator instanceof SimpleItemAnimator) {
                ((SimpleItemAnimator) itemAnimator).setSupportsChangeAnimations(false);
            }
        }
    }


    /***
     * 由于后续阿语的数字format用跟英文保持一致，所以这里新加了一个getNumberFormat方法
     * @param res
     * @param number
     * @return
     */
    public static String getNumberFormat(@StringRes int res, int number) {
        String str = ResourceUtils.getString(res);
        return String.format(isRTL() ? Locale.ENGLISH : Locale.getDefault(), str, number);
    }


    /**
     * 通用的适配文本方向的方法
     * @param textView
     * @param text
     */
    public static void setText(TextView textView, CharSequence text) {
        textView.setText(text);
        textView.setTextDirection(View.TEXT_DIRECTION_LOCALE);
    }


    /**
     * 加这个方法是因为不信任服务端的color，要做兜底处理
     */
    public static void setTextColor(TextView textView, String color) {
        try {
            if (!TextUtils.isEmpty(color)) {
                textView.setTextColor(Color.parseColor(color));
            }
        } catch (Exception ignore) {
        }
    }
}
